﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MinistryStandardPlatformBusiness.Helper;
using MinistryStandardPlatformBusiness.MessagePool.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MinistryStandardPlatformBusiness.MessagePool.QueueSession
{
    public class UserRightSession
    {
        private string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        private List<string> rightSims;

        public List<string> RightSims
        {
            get { return rightSims; }
            set { rightSims = value; }
        }
    }
    public class OnLineUser
    {
        private string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }
        private string guid;

        public string Guid
        {
            get { return guid; }
            set { guid = value; }
        }
        private string type;

        public string Type
        {
            get { return type; }
            set { type = value; }
        }
    }
    public class UserSession
    {
        #region 缓存及基本配置
        public static List<UserRightSession> UserVechielRightSession = new List<UserRightSession>();//用户权限缓存
        public static List<LatestGpsInfo> LatestGpsInfoList = new List<LatestGpsInfo>();
        public static Dictionary<string, LatestGpsInfo> LatestGpsInfoDic = new Dictionary<string, LatestGpsInfo>();
        public static List<OnLineUser> OnlineUserListSession = new List<OnLineUser>();

        public static string BusinessEndPoint = "tcp://59.69.105.80:5555";//业务中心
        public static string ClientLocalPoint = "tcp://*:5557";//订阅发布,发布版 -3
        public static string ClientPubSubPoint = "tcp://*:5556";//客户端web双向通信 ,发布版 -3
        public static int MaxQueLen = 896000;//消息队列
        public static string LogPath = "D:\\LogH\\";//日志记录
        public static bool isCouludCatchWorked = false;

        private static System.Timers.Timer gpsdbCatchTimer;
        #endregion
        #region 根据用户名获取在线车辆的实时信息
        /// <summary>
        /// 根据用户名获取在线车辆的实时信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns>json格式的数据</returns>
        public static List<LatestGpsInfo> getLatestGPSInfoForOnlineUser(string userName)
        {
            List<LatestGpsInfo> temp = new List<LatestGpsInfo>();
            if (userName.Length < 1 || userName == "")
            {
                return null;
            }
            else
            {
                //获取在线用户的在线车辆的实时信息
                try
                {
                    List<string> ls = new List<string>();
                    ls.AddRange(UserVechielRightSession.Where(p => p.Username.Equals(userName)).SelectMany(p => p.RightSims));
                    temp.AddRange(LatestGpsInfoDic.Where(p => ls.Contains(p.Key)).Select(p => p.Value));
                }
                catch (Exception e)
                {
                    Log.WriteLog("getLatestGPSInfoForOnlineUser", e.Message.ToString());
                }
            }

            return temp;
        }

        public static string getLatestGPSInfoForOnlineUserJson(string userName)
        {
            return JsonConvert.SerializeObject(getLatestGPSInfoForOnlineUser(userName));
        }

        #endregion


        #region 在线用户及权限缓存维护
        /// <summary>
        /// 供心跳使用,频繁调用，减少判定次数,维护在线用户,及车辆缓存
        /// </summary>
        /// <param name="jsonStr"></param>
        public static void onLineUserHanderForJson(string jsonStr)
        {
            try
            {
                JObject jo = JObject.Parse(jsonStr);
                if (jo["Userid"] != null)
                {
                    if (!OnlineUserListSession.Exists(
                        p => p.Username.Equals(jo["Userid"].ToString()
                            ) && p.Guid.Equals(jo["Guid"].ToString())
                            ))
                    {//若不存在，则添加
                        OnLineUser tempOnLineUser = new OnLineUser();
                        tempOnLineUser.Guid = jo["Guid"].ToString();
                        tempOnLineUser.Username = jo["Userid"].ToString();
                        tempOnLineUser.Type = jo["LoginType"].ToString();
                        lock (OnlineUserListSession)
                        {
                            OnlineUserListSession.Add(tempOnLineUser);
                        }
                        System.Threading.Thread RightThread =
                            new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(getRightSimsByUserName));
                        RightThread.IsBackground = true;
                        RightThread.Start(tempOnLineUser.Username);

                        Log.WriteLog("Login", tempOnLineUser.Username + "|=|" + tempOnLineUser.Guid + "|=|" + tempOnLineUser.Type);
                    }
                }
            }
            catch (Exception e)
            {
                Log.WriteLog("onLineUserHanderForJson", e.ToString());
            }

        }

        public static void onLineUserHanderForEntity(string userid = "e", string guid = "e", int loginType = 2)
        {
            //判断在线用户缓存是否有该账号，考虑账号类型，若不在线则添加至缓存中 20140709
            bool isExits = false;
            lock (OnlineUserListSession)
            {
                isExits = OnlineUserListSession.Exists(p => p.Guid.Equals(guid));
            }
            if (!isExits)
            {//如果缓存表中不存在该账号
                #region 添加并更新缓存
                try
                {
                    OnLineUser tempOnLineUser = new OnLineUser();
                    tempOnLineUser.Guid = guid;
                    tempOnLineUser.Username = userid;
                    tempOnLineUser.Type = loginType.ToString();
                    lock (OnlineUserListSession)
                    {
                        OnlineUserListSession.Add(tempOnLineUser);
                    }
                    //后期可优化
                    System.Threading.Thread RightThread =
                                     new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(getRightSimsByUserName));
                    RightThread.IsBackground = true;
                    RightThread.Start(tempOnLineUser.Username);

                    MinistryStandardPlatformBusiness.Helper.Log.WriteLog("Login", tempOnLineUser.Username + "|=|" + tempOnLineUser.Guid + "|=|" + tempOnLineUser.Type);

                }
                catch (Exception e)
                {
                    Log.WriteLog("onLineUserHanderForWeb", e.ToString());
                }
                #endregion
            }
        }

        /// <summary>
        /// 获取账号内车辆权限，并添加到缓存。
        /// </summary>
        /// <param name="userNameOBJ"></param>
        private static void getRightSimsByUserName(object userNameOBJ)
        {
            string userName = userNameOBJ as string;
            string ReStr;
            ReStr = DBHelper.GlobalDBWCFHelper.BexecuteProc(userName, "getVehiclesSimWithRight");

            if (!ReStr.Equals("error"))
            {
                ReStr = JsonHelper.JsonTableToJson(ReStr);
                if (ReStr != "")
                {
                    UserRightSession tempUserRightSims = new UserRightSession();
                    tempUserRightSims.RightSims = JsonHelper.getListSingleStr(ReStr);
                    tempUserRightSims.Username = userName;

                    lock (UserVechielRightSession)
                    {//将权限内的sim卡号添加至缓存
                        UserVechielRightSession.Add(tempUserRightSims);
                    }
                }
            }
            else
            {
                Log.WriteLog("getRightSimsByUserName", userName);
            }
        }
        public static void onLineUserHander()
        {
            string ss = string.Empty;

            foreach (OnLineUser item in OnlineUserListSession)
            {
                ss = item.Username + "|===|" + item.Guid + "|===|" + item.Type + "||";
            }
            Log.WriteLog("onLineUserHander", ss);
            lock (OnlineUserListSession)
            {
                OnlineUserListSession.Clear();
            }

            lock (UserVechielRightSession)
            {
                UserVechielRightSession.Clear();
            }
        }

        public static string registerHander(string jsonStr)
        {
            string reStr = "0";
            List<LatestGpsInfo> lg = new List<LatestGpsInfo>();
            try
            {
                JObject jo = JObject.Parse(jsonStr);
                lg = WebSessionHander.getRealtimeGPSinfoByUserid(jo["Userid"].ToString());
                //lg.AddRange(lg);
                JObject sjo = new JObject();
                sjo.Add("GType", "Register");
                sjo.Add("GpsBasic", JsonConvert.SerializeObject(lg));
                sjo.Add("GpsAttatch", "");
                reStr = sjo.ToString();
                Log.WriteLog("registerHanderOk", reStr);
            }
            catch (Exception e)
            {
                Log.WriteLog("registerHanderError", e.ToString());
            }
            return reStr;
        }
        #endregion

        #region  初次启动时的缓存加载
        /// <summary>
        /// 1.以admin读取所有车辆;
        /// 2.根据sim获取缓存
        /// </summary>
        public static List<LatestGpsInfo> getLatestInfoFromGpsBasic(List<string> simsList)
        {
            List<LatestGpsInfo> lgs = new List<LatestGpsInfo>();
            string dbase = "[MinistryStandardPlatformGps" + DateTime.Now.ToString("yyyyMM") + "].[dbo].[GpsBasic]";

            string sims = "('" + simsList[0] + "'";
            for (int i = 1; i < simsList.Count; i++)
            {
                sims += (",'" + simsList[i] + "'");
            }
            sims += ")";
            string sql = "select vehicleId as VehicleId,altitude as Altitude,devSpeed as DevSpeed,direction as Direction,mileage as Distance,gpsmileage as GpsDistance,latitude as Latitude," +
                         "longitudeoffset as Nlongitude,latitudeoffset as Nlatitude,longitude as Longitude,oilVolumn as Oil,attachOil as AttachOil,'' as SatelliteNum,'' as SignalStrength," +
                         "simId as SimId,speed as Speed,recordtime as UpTime,warninfo as WarnSign,'' as Poi,statusinfo as StatusSign,vehicleNum as vehicleNum,battery as battery " +
                         "from " + dbase +
                         " t1 where simId in" + sims + " and recordtime=(select max(recordtime) from "+dbase+" t2 where t2.simId= t1.simId) ";
            string re = "";
            try
            {
                using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                {
                    re = client.BexcuteSql("admin", sql);
                }
            }
            catch (Exception e)
            {
                Log.WriteLog("getLatestInfoFromGpsBasicError", e.ToString());
            }
            re = re.Substring(1, re.Length - 2);
            Log.WriteLog("getLatestInfoFromGpsBasicDetails", re);
            if (!re.ToLower().Contains("error"))
            {
                try
                {
                    lgs = JsonHelper.JsonStrToObject<List<LatestGpsInfo>>(re);

                    //地理解析
                    for (int i = lgs.Count - 1; i >= 0;i-- )
                    {
                        if (lgs[i] != null && lgs[i].IsValid())
                        {
                            LngLatPoi mLngLatPoi = MessagePublish.TransGeoPoiHander(lgs[i].Nlongitude, lgs[i].Nlatitude, "1");
                            lgs[i].Poi = mLngLatPoi.poi;
                        }
                        else
                        {
                            lgs.Remove(lgs[i]);
                        }
                    }
                    return lgs;
                }
                catch (Exception e)
                {
                    Log.WriteLog("getLatestInfoFromGpsBasicError", e.ToString());
                    return null;
                }
            }
            else
            {
                return null;
            }
        }



        /// <summary>
        /// 1.以admin读取所有车辆;
        /// 2.根据sim获取缓存
        /// </summary>
        /// 
        public static void initGpsLocationCache()
        {
            string ReStr;
            using (DBService.DBHelperClient client = new DBService.DBHelperClient())
            {
                try
                {//获取权限内的所有车 
                    ReStr = client.BexecuteProc("admin", "getVehiclesSimWithRight");
                    Log.WriteLog("vehiclesInRights", ReStr);

                }
                catch (Exception e)
                {
                    Log.WriteLog("initGpsLocationCacheError", e.ToString());
                    ReStr = "error";
                }
            }
            if (ReStr != null && !ReStr.Equals("error"))
            {
                //
                DataTable dt = new DataTable();
                dt = JsonHelper.JsonToDataTable(ReStr);
                if (dt.Rows.Count > 0)
                {
                    List<string> needQuerySims = new List<string>();
                    string sims = "('" + dt.Rows[0][0].ToString() + "'";
                    needQuerySims.Add(dt.Rows[0][0].ToString());
                    for (int i = 1; i < dt.Rows.Count; i++)
                    {
                        sims += (",'" + dt.Rows[i][0].ToString() + "'");
                        needQuerySims.Add(dt.Rows[i][0].ToString());
                    }
                    sims += ")";

                    string sql = "select vehicleId as VehicleId,altitude as Altitude,devSpeed as DevSpeed,direction as Direction,distance as Distance,gpsDistance as GpsDistance,"+
                        "latitude as Latitude,nlongitude as Nlongitude,nlatitude as Nlatitude,longitude as Longitude,Oil as Oil,attachOil as AttachOil,satelliteNum as SatelliteNum,signalStrength as SignalStrength,"+
                        "simId as SimId,speed as Speed,uptime as UpTime,warnsign as WarnSign,POI as Poi,statusSign as StatusSign,vehicleNum as vehicleNum,battery as battery from GpsinfoCatch where simid in" + sims;
                    string re = "";

                    try
                    {
                        using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                        {
                            re = client.BexcuteSql("admin", sql);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.WriteLog("initGpsLocationCacheError", e.ToString());
                    }

                    Log.WriteLog("initGpsLocationCacheDetails", re);
                    List<LatestGpsInfo> lgs = new List<LatestGpsInfo>();
                    List<string> validSims =new List<string>();
                    if (re != "[]" && !re.ToLower().Contains("error"))
                    {
                        try
                        {
                            //lgs = GpsInfoHelper.DeJsonToLatestGpsInfoList(JsonHelper.JsonToDataTable(re),out validSims);
                            re = re.Substring(1, re.Length - 2);
                            lgs = JsonHelper.JsonStrToObject<List<LatestGpsInfo>>(re);

                            for (int i = lgs.Count - 1; i >= 0;i-- )
                            {
                                if (lgs[i] != null && lgs[i].IsValid())
                                {
                                    validSims.Add(lgs[i].SimId);
                                }
                                else
                                {
                                    lgs.Remove(lgs[i]);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Log.WriteLog("initGpsLocationCacheError", e.ToString());
                        }
                        Log.WriteLog("lgsinit", JsonHelper.ListToJsonStr(lgs));
                        List<string> needReQuerySims = new List<string>();
                        for (int i = 0; i < needQuerySims.Count; i++)
                        {
                            if (!validSims.Contains(needQuerySims[i]))
                            {
                                needReQuerySims.Add(needQuerySims[i]);
                            }
                        }

                        //不合法的数据从当月的gpsbasic表中查询获取
                        List<LatestGpsInfo> tmp = getLatestInfoFromGpsBasic(needReQuerySims);
                        Log.WriteLog("lgsbasic", JsonHelper.ListToJsonStr(tmp));
                        lgs.AddRange(tmp);
                        //Log.WriteLog("getLatestInfoFromGpsBasicFinish", "finish at:" + DateTime.Now.ToString());
                        Log.WriteLog("lgs", JsonHelper.ListToJsonStr(tmp));
                        for (int i = 0; i < lgs.Count;i++ )
                        {
                            //Log.WriteLog("LatestGpsInfoDicAll", lgs[i].SimId);
                            if (!LatestGpsInfoDic.ContainsKey(lgs[i].SimId))
                            {
                                try
                                {
                                    LatestGpsInfoDic.Add(lgs[i].SimId, lgs[i]);
                                    //Log.WriteLog("LatestGpsInfoDic", lgs[i].SimId);
                                }
                                catch (Exception ex)
                                {
                                    //Log.WriteLog("LatestGpsInfoDic", ex.Message);

                                }
                            }
                        }
                    }
                }

            }

            //Log.WriteLog("initGpsLocationCacheFinish", "finish at:" + DateTime.Now.ToString());
            initDataBaseCatch();
        }

        //public static void initGpsLocationCacheOld1()
        //{
        //    string ReStr;
        //    using (DBService.DBHelperClient client = new DBService.DBHelperClient())
        //    {
        //        try
        //        {//获取权限内的所有车 
        //            ReStr = client.BexecuteProc("admin", "getVehiclesSimWithRight");
        //            Log.WriteLog("vehiclesInRights", ReStr);

        //        }
        //        catch (Exception e)
        //        {
        //            Log.WriteLog("initGpsLocationCacheError", e.ToString());
        //            ReStr = "error";
        //        }
        //    }
        //    if (ReStr != null && !ReStr.Equals("error"))
        //    {
        //        //
        //        DataTable dt = new DataTable();
        //        dt = JsonHelper.JsonToDataTable(ReStr);
        //        if (dt.Rows.Count > 0)
        //        {
        //            #region //根据sim卡号并行初始化缓存
        //            System.Threading.Tasks.Parallel.For(0, dt.Rows.Count, (i) =>
        //            {
        //                //for(int i=0;i<dt.Rows.Count;i++)
        //                //{
        //                #region
        //                Log.WriteLog("vehiclesIndex", i.ToString());
        //                LatestGpsInfo lg = new LatestGpsInfo();
        //                string sim = dt.Rows[i][0].ToString();

        //                string sql = "select top 1 * from GpsinfoCatch where simid = '" + sim + "' order by inserttime desc ";
        //                string re = "";
        //                try
        //                {
        //                    using (DBService.DBHelperClient client = new DBService.DBHelperClient())
        //                    {
        //                        re = client.BexcuteSql("admin", sql);
        //                    }
        //                }
        //                catch (Exception e)
        //                {
        //                    Log.WriteLog("initGpsLocationCacheError", e.ToString());
        //                }
        //                Log.WriteLog("initGpsLocationCacheDetails", re);
        //                if (re != "[]" && !re.ToLower().Contains("error"))
        //                {
        //                    DataTable dtRe = new DataTable();
        //                    try
        //                    {
        //                        dtRe = JsonHelper.JsonToDataTable(re);
        //                        lg = GpsInfoHelper.DeJsonToLatestGpsInfo(JsonHelper.JsonToDataTable(re));
        //                    }
        //                    catch (Exception e)
        //                    {
        //                        Log.WriteLog("initGpsLocationCacheError", e.ToString());
        //                    }

        //                    //如果从缓存表中读取不合法
        //                    if (lg == null || lg.Latitude == "0" || lg.Longitude == "0" || lg.Nlatitude == "0" || lg.Nlongitude == "0")
        //                    {
        //                        //从gpsbasic表中读取最近一条数据
        //                        lg = getLatestInfoFromGpsBasic(sim);
        //                    }
        //                    //lock (LatestGpsInfoDic)
        //                    //{//若不存在，则添加
        //                    if (lg != null && !LatestGpsInfoDic.ContainsKey(lg.SimId))
        //                    {
        //                        try
        //                        {
        //                            LatestGpsInfoDic.Add(lg.SimId, lg);
        //                        }
        //                        catch { }
        //                    }
        //                    Log.WriteLog("InitLatestGpsInfo", JsonConvert.SerializeObject(lg));
        //                    //}
        //                }
        //                //如果从缓存表中读出的数据为空或读取出错
        //                else
        //                {
        //                    //从gpsbasic表中读取最近一条数据
        //                    lg = getLatestInfoFromGpsBasic(sim);
        //                    //lock (LatestGpsInfoDic)
        //                    //{//若不存在，则添加
        //                    if (lg != null && !LatestGpsInfoDic.ContainsKey(lg.SimId))
        //                    {
        //                        try
        //                        {
        //                            LatestGpsInfoDic.Add(lg.SimId, lg);
        //                        }
        //                        catch
        //                        { }
        //                    }
        //                    Log.WriteLog("InitLatestGpsInfo", JsonConvert.SerializeObject(lg));
        //                    //}
        //                }
        //                #endregion
        //            });
        //            initDataBaseCatch();
        //            Log.WriteLog("initGpsLocationCache", "ok");
        //            #endregion
        //        }

        //    }
        //}

        public static void initGpsLocationCacheOld()
        {
            string ReStr;
            using (DBService.DBHelperClient client = new DBService.DBHelperClient())
            {
                try
                {//获取权限内的所有车 
                    ReStr = client.BexecuteProc("admin", "getVehiclesSimWithRight");
                }
                catch (Exception e)
                {
                    Log.WriteLog("initGpsLocationCacheError", e.ToString());
                    ReStr = "error";
                }
            }
            if (ReStr != null && !ReStr.Equals("error"))
            {
                //
                DataTable dt = new DataTable();
                dt = JsonHelper.JsonToDataTable(ReStr);
                if (dt.Rows.Count > 0)
                {
                    #region //根据sim卡号并行初始化缓存
                    System.Threading.Tasks.Parallel.For(0, dt.Rows.Count, (i) =>
                    {
                        #region
                        LatestGpsInfo lg = new LatestGpsInfo();
                        string sim = dt.Rows[i][0].ToString();

                        string sql = "SELECT TOP 1 vehicleId,vehicleNum,altitude,devSpeed,direction,mileage,gpsmileage,latitude,longitudeoffset,latitudeoffset,longitude,oilVolumn,attachOil,simId,speed,convert(varchar(40),inserttime,121) as inserttime,warninfo,statusinfo,battery FROM [GpsBasic] where simid = '" + sim + "' order by inserttime desc ";
                        string re = "";
                        try
                        {
                            using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                            {
                                re = client.YExecuteReportSql("admin", DateTime.Now, DateTime.Now, sql, "1");
                            }
                        }
                        catch (Exception e)
                        {
                            Log.WriteLog("initGpsLocationCacheError", e.ToString());
                        }
                        Log.WriteLog("initGpsLocationCacheDetails", re);
                        if (re != "[]" && !re.ToLower().Contains("error"))
                        {
                            DataTable dtRe = new DataTable();
                            dtRe = JsonHelper.JsonToDataTable(re);
                            lg = GpsInfoHelper.DeJsonToLatestGpsInfoOld(JsonHelper.JsonToDataTable(re));

                            lock (LatestGpsInfoDic)
                            {//若不存在，则添加
                                if (lg != null && !LatestGpsInfoDic.ContainsKey(lg.SimId))
                                    LatestGpsInfoDic.Add(lg.SimId, lg);
                            }
                        }
                        #endregion
                    });
                    initDataBaseCatch();//更新数据库缓存
                    Log.WriteLog("initGpsLocationCache", "ok");
                    #endregion
                }

            }
        }
        #endregion

        #region 初始化缓存入库
        public static void initDataBaseCatch()
        {
            gpsdbCatchTimer = new System.Timers.Timer(10 * 60 * 1000);//10分钟更新一次
            gpsdbCatchTimer.Elapsed += new System.Timers.ElapsedEventHandler(UserSession.initDataBaseCatch);
            gpsdbCatchTimer.AutoReset = true;
            gpsdbCatchTimer.Enabled = true;
            UserSession.initDataBaseCatch(null, null);
            
        }
        /// <summary>
        /// 初始化最新缓存入库
        /// </summary>
        public static void initDataBaseCatch(object source, System.Timers.ElapsedEventArgs e)
        {
            //Log.WriteLog("LatestGpsInfoListDetails", "start at:" + DateTime.Now.ToString());
            try
            {
                //lock (LatestGpsInfoDic)
                //{
                LatestGpsInfoList.Clear();
                LatestGpsInfoList.AddRange(LatestGpsInfoDic.Values);
                //}
                Log.WriteLog("LatestGpsInfoListDetails", JsonHelper.ListToJsonStr(LatestGpsInfoList));
            }
            catch (Exception ex)
            {
                Log.WriteLog("LatestGpsInfoListDetails", "error:"+ex.Message);
            }
            try
            {
                //using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                //{
                //    client.BexcuteSql("admin", "delete  from gpsinfoCatch");
                //}

                System.Threading.Tasks.Parallel.ForEach(LatestGpsInfoList, (lgt) =>
                {
                    string sql = buildSqlForLatestInfo(lgt);
                    if (sql != null)
                    {
                        try
                        {
                            using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                            {
                                client.BexcuteSql("admin", sql);
                            }
                        }
                        catch (Exception)
                        {
                            Log.WriteLog("initDataBaseCatch_error", lgt.SimId);
                        }
                    }
                });
            }
            catch (Exception ee)
            {

                Log.WriteLog("initDataBaseCatch_DeleteError", ee.ToString());
            }


        }
        private static string buildSqlForLatestInfo(LatestGpsInfo lgt)
        {
            string sql = "";

            sql = "insert into GpsinfoCatch(altitude,devSpeed,direction,distance," +
                "gpsDistance,longitude,latitude,nlatitude,nlongitude,oil,attachOil,satelliteNum,"
                + "signalStrength,simId,speed,uptime,poi,warnsign,statusSign,vehicleId,vehicleNum, battery) values";
            string attchStr = "";
            try
            {
                using (DBService.DBHelperClient client = new DBService.DBHelperClient())
                {
                    client.BexcuteSql("admin", "delete   from gpsinfoCatch where simId ='" + lgt.SimId + "'");
                }
                #region
                attchStr += "'";
                attchStr += lgt.Altitude == null ? "null" : lgt.Altitude;
                attchStr += "','";
                attchStr += lgt.DevSpeed == null ? "null" : lgt.DevSpeed;
                attchStr += "','";
                attchStr += lgt.Direction == null ? "null" : lgt.Direction;
                attchStr += "','";
                attchStr += lgt.Distance == null ? "null" : lgt.Distance;
                attchStr += "','";

                attchStr += lgt.GpsDistance == null ? "null" : lgt.GpsDistance;
                attchStr += "','";
                attchStr += lgt.Longitude == null ? "null" : lgt.Longitude;
                attchStr += "','";
                attchStr += lgt.Latitude == null ? "null" : lgt.Latitude;
                attchStr += "','";
                attchStr += lgt.Nlatitude == null ? "null" : lgt.Nlatitude;
                attchStr += "','";
                attchStr += lgt.Nlongitude == null ? "null" : lgt.Nlongitude;
                attchStr += "','";
                attchStr += lgt.Oil == null ? "null" : lgt.Oil;
                attchStr += "','";
                attchStr += lgt.AttachOil == null ? "null" : lgt.AttachOil;
                attchStr += "','";
                attchStr += lgt.SatelliteNum == null ? "null" : lgt.SatelliteNum;
                attchStr += "','";

                attchStr += lgt.SignalStrength == null ? "null" : lgt.SignalStrength;
                attchStr += "','";
                attchStr += lgt.SimId == null ? "null" : lgt.SimId;
                attchStr += "','";
                attchStr += lgt.Speed == null ? "null" : lgt.Speed;
                attchStr += "','";
                attchStr += lgt.UpTime == null ? "null" : lgt.UpTime;
                attchStr += "','";
                attchStr += lgt.Poi == null ? "null" : lgt.Poi;
                attchStr += "','";
                attchStr += lgt.WarnSign == null ? "null" : lgt.WarnSign;
                attchStr += "','";
                attchStr += lgt.StatusSign == null ? "null" : lgt.StatusSign;
                attchStr += "','";
                attchStr += lgt.VehicleId == null ? "null" : lgt.VehicleId;
                attchStr += "','";
                attchStr += lgt.vehicleNum == null ? "null" : lgt.vehicleNum;
                attchStr += "','";
                attchStr += lgt.battery == null ? "null" : lgt.battery;
                attchStr += "'";
                sql += "(" + attchStr + ")";
                //Log.WriteLog("buildSqlForLatestInfo", sql);
                #endregion
            }
            catch (Exception e)
            {
                Log.WriteLog("buildSqlForLatestInfo_Error", e.ToString());
                return null;
            }

            return sql;
        }
        #endregion
    }
}

